import express from 'express';
import { body, validationResult, query, param } from 'express-validator';
import { Expert, Domain } from '../models/index.js';
import { authenticateAdmin } from '../middleware/auth.js';
import { uploadAvatar, uploadDisplayImages } from '../middleware/upload.js';
import { catchAsync, BusinessError, NotFoundError } from '../middleware/errorHandler.js';
import { Op } from 'sequelize';
import { success, paginated } from '../utils/response.js';
import { processExpertImageUrls, generateImageUrl, generateImageUrls } from '../utils/imageUrl.js';

const router = express.Router();

// 手机端公开接口已移至 /api/mobile/experts/

// 管理员接口 - 获取所有专家列表
router.get('/admin/list',
  authenticateAdmin,
  [
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
    query('domain_id').optional().isInt({ min: 1 }).withMessage('领域ID必须是正整数'),
    query('is_enabled').optional().custom((value) => {
      if (value === null || value === undefined || value === '') return true;
      if (value === 'true' || value === 'false' || value === true || value === false) return true;
      throw new Error('状态参数必须是布尔值');
    }),
    query('keyword').optional().isLength({ max: 100 }).withMessage('关键词不能超过100个字符')
  ],
  catchAsync(async (req, res) => {
    const { page = 1, limit = 20, domain_id, is_enabled, keyword } = req.query;
    const where = {};
    
    if (domain_id) {
      where.domain_id = domain_id;
    }
    
    if (is_enabled !== undefined) {
      where.is_enabled = is_enabled === 'true';
    }
    
    if (keyword) {
      where[Op.or] = [
        { nickname: { [Op.like]: `%${keyword}%` } },
        { bio: { [Op.like]: `%${keyword}%` } }
      ];
    }
    
    const result = await Expert.findAndCountAll({
      where,
      include: [{
        association: 'domain',
        attributes: ['id', 'name']
      }],
      order: [['sort_order', 'ASC'], ['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: (parseInt(page) - 1) * parseInt(limit)
    });

    // 处理专家列表中的图片URL
    const processedExperts = await Promise.all(
      result.rows.map(expert => processExpertImageUrls(expert.toJSON()))
    );

    res.json(paginated(processedExperts, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: result.count,
      pages: Math.ceil(result.count / parseInt(limit))
    }, '获取专家列表成功'));
  })
);

// 管理员接口 - 创建专家
router.post('/admin/create',
  authenticateAdmin,
  [
    body('domain_id')
      .isInt({ min: 1 })
      .withMessage('领域ID必须是正整数'),
    body('nickname')
      .notEmpty()
      .withMessage('专家昵称不能为空')
      .isLength({ max: 100 })
      .withMessage('专家昵称不能超过100个字符'),
    body('bio')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('简介不能超过1000个字符'),
    body('welcome_message')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('欢迎语不能超过1000个字符'),
    body('classic_cases')
      .optional()
      .custom((value) => {
        if (value === null || value === undefined) return true;
        if (Array.isArray(value)) return true;
        throw new Error('经典案例必须是数组');
      }),
    body('sort_order')
      .optional()
      .isInt({ min: 0 })
      .withMessage('排序权重必须是非负整数'),
    body('is_enabled')
      .optional()
      .custom((value) => {
        if (value === null || value === undefined) return true;
        if (value === true || value === false) return true;
        throw new Error('启用状态必须是布尔值');
      }),
    body('external_expert_id')
      .optional()
      .isLength({ max: 100 })
      .withMessage('外部专家ID不能超过100个字符'),
    body('avatar_url')
      .optional()
      .isLength({ max: 500 })
      .withMessage('头像URL不能超过500个字符'),
    body('display_images')
      .optional()
      .custom((value) => {
        if (value === null || value === undefined) return true;
        if (Array.isArray(value)) return true;
        throw new Error('展示图片必须是数组');
      })
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const expertData = req.body;
    
    // 检查领域是否存在
    const domain = await Domain.findByPk(expertData.domain_id);
    if (!domain) {
      throw new BusinessError('指定的领域不存在');
    }
    
    const expert = await Expert.create(expertData);
    
    res.json(success(expert, '专家创建成功'));
  })
);

// 管理员接口 - 更新专家
router.put('/admin/:id',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('专家ID必须是正整数'),
    body('domain_id')
      .optional()
      .isInt({ min: 1 })
      .withMessage('领域ID必须是正整数'),
    body('nickname')
      .optional()
      .notEmpty()
      .withMessage('专家昵称不能为空')
      .isLength({ max: 100 })
      .withMessage('专家昵称不能超过100个字符'),
    body('bio')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('简介不能超过1000个字符'),
    body('welcome_message')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('欢迎语不能超过1000个字符'),
    body('classic_cases')
      .optional()
      .custom((value) => {
        if (value === null || value === undefined) return true;
        if (Array.isArray(value)) return true;
        throw new Error('经典案例必须是数组');
      }),
    body('sort_order')
      .optional()
      .isInt({ min: 0 })
      .withMessage('排序权重必须是非负整数'),
    body('is_enabled')
      .optional()
      .custom((value) => {
        if (value === null || value === undefined) return true;
        if (value === true || value === false) return true;
        throw new Error('启用状态必须是布尔值');
      }),
    body('external_expert_id')
      .optional()
      .isLength({ max: 100 })
      .withMessage('外部专家ID不能超过100个字符'),
    body('avatar_url')
      .optional()
      .isLength({ max: 500 })
      .withMessage('头像URL不能超过500个字符'),
    body('display_images')
      .optional()
      .custom((value) => {
        if (value === null || value === undefined) return true;
        if (Array.isArray(value)) return true;
        throw new Error('展示图片必须是数组');
      })
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { id } = req.params;
    const updateData = req.body;
    
    const expert = await Expert.findByPk(id);
    if (!expert) {
      throw new NotFoundError('专家不存在');
    }
    
    // 如果更新领域，检查领域是否存在
    if (updateData.domain_id && updateData.domain_id !== expert.domain_id) {
      const domain = await Domain.findByPk(updateData.domain_id);
      if (!domain) {
        throw new BusinessError('指定的领域不存在');
      }
    }
    
    await expert.update(updateData);
    
    res.json(success(expert, '专家更新成功'));
  })
);

// 管理员接口 - 删除专家
router.delete('/admin/:id',
  authenticateAdmin,
  [
    param('id').isInt({ min: 1 }).withMessage('专家ID必须是正整数'),
    body('password').notEmpty().withMessage('密码不能为空')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { id } = req.params;
    const { password } = req.body;

    // 验证管理员密码
    const isValidPassword = await req.admin.validatePassword(password);
    if (!isValidPassword) {
      throw new BusinessError('密码错误，无法执行删除操作');
    }

    const expert = await Expert.findByPk(id);
    if (!expert) {
      throw new NotFoundError('专家不存在');
    }

    await expert.destroy();

    res.json(success(null, '专家删除成功'));
  })
);

// 管理员接口 - 上传专家头像
router.post('/admin/:id/avatar',
  authenticateAdmin,
  uploadAvatar,
  [
    param('id').isInt({ min: 1 }).withMessage('专家ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const { id } = req.params;

    if (!req.file) {
      throw new BusinessError('请选择要上传的头像文件');
    }

    const expert = await Expert.findByPk(id);
    if (!expert) {
      throw new NotFoundError('专家不存在');
    }

    // 生成完整的头像URL
    const fullAvatarUrl = await generateImageUrl(req.file.url);

    // 更新头像URL（存储相对路径）
    expert.avatar_url = req.file.url;
    await expert.save();

    res.json(success({ avatar_url: fullAvatarUrl }, '头像上传成功'));
  })
);

// 管理员接口 - 上传专家展示图片
router.post('/admin/:id/display-images',
  authenticateAdmin,
  uploadDisplayImages,
  [
    param('id').isInt({ min: 1 }).withMessage('专家ID必须是正整数')
  ],
  catchAsync(async (req, res) => {
    const { id } = req.params;

    if (!req.files || req.files.length === 0) {
      throw new BusinessError('请选择要上传的图片文件');
    }

    const expert = await Expert.findByPk(id);
    if (!expert) {
      throw new NotFoundError('专家不存在');
    }

    // 生成完整的展示图片URLs
    const relativeUrls = req.files.map(file => file.url);
    const fullImageUrls = await generateImageUrls(relativeUrls);

    // 更新展示图片URLs（存储相对路径）
    expert.display_images = relativeUrls;
    await expert.save();

    res.json(success({ display_images: fullImageUrls }, '展示图片上传成功'));
  })
);

export default router;
